# -*- coding: utf-8 -*-
# python3

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pandas as pd
from PIL import Image
from selenium import webdriver
import time
import os
from aip import AipOcr#pip install baidu-aip
"""设置APPID API_KEY SECRET_KEY（到百度AI申请，使用免费版就好，QPS够用）
    链接：https://ai.baidu.com/tech/ocr/general  """
APP_ID = ""
API_KEY = ""
SECRET_KEY = ""

def main():
    nameListFile = r'复试上线考生名单.xlsx'
    Query(nameListFile)

def Query(nameListFile):
    def wait_element(xpath, timeout=15):
        return WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.XPATH, xpath)))


    names = pd.read_excel(nameListFile)
    nameList = []
    #打开浏览器
    login_url = "https://yz.scu.edu.cn/score"
    driver = webdriver.Chrome(r"chromedriver.exe")
    driver.get(login_url)
    driver.maximize_window()

    Political = []#政治
    English = []#英语
    Math = []#数学
    ProfCourse = []#专业课
    Total = []#总分

    C_number = []#考号
    print('\t'.join(['姓名',"考生编号","专业","政治","英语","数学","专业课","总分"]))
    for per in names.values:
        name, c_num,major,_ = per
        nameList.append([name,str(c_num),major])
        ele = wait_element('//*[@id="ksbh"]')
        ele.send_keys(Keys.CONTROL + 'a')  # CTRL + a ：全选
        ele.send_keys(Keys.DELETE)  # 删除
        ele.send_keys(c_num)#考号
        C_number.append(str(c_num))
        ele = wait_element('//*[@id="xm"]')
        ele.send_keys(Keys.CONTROL + 'a')  # CTRL + a ：全选
        ele.send_keys(Keys.DELETE)  # 删除
        ele.send_keys(name)  # 姓名
        wait_element('//*[@id="vcode"]').click()

        while True:#验证码处理
            time.sleep(0.3)
            wait_element('/html/body/div/div[2]/div[1]/div[1]/table/tbody/tr[4]/td[2]/span[2]/span').click()  # 点击换一张
            #获取验证码
            img_png=driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[1]/table/tbody/tr[4]/td[2]/span[2]/img').screenshot_as_png
            #识别验证码
            c_rlt = RecogVCode(img_png)
            if not c_rlt:#识别失败
                continue
            ele = wait_element('//*[@id="vcode"]')
            ele.send_keys(Keys.CONTROL + 'a')  # CTRL + a ：全选
            ele.send_keys(Keys.DELETE)  # 删除
            ele.send_keys(c_rlt)  # 输入验证码
            wait_element('//*[@id="submit"]').click()
            time.sleep(0.3)
            try:
                ele = driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/div[1]')
                if ele.text.strip() =='校验码错误或失效！':
                    continue
            except Exception:
                continue
            break
        Political.append(int(driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/table/tbody/tr[1]/td[3]/span').text))
        English.append(int(driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/table/tbody/tr[2]/td[3]/span').text))
        Math.append(int(driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/table/tbody/tr[3]/td[3]/span').text))
        ProfCourse.append(int(driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/table/tbody/tr[4]/td[3]/span').text))
        Total.append(int(driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[2]/div/table/tbody/tr[5]/td[2]/span').text))
        print('\t'.join(nameList[-1])+'\t'+str(Political[-1])+'\t'+str(English[-1])+'\t'+str(Math[-1])+'\t'+str(ProfCourse[-1])+'\t'+str(Total[-1]))

    # 新增列
    names['政治'] = Political
    names['英语'] = English
    names['数学'] = Math
    names['专业课'] = ProfCourse
    names['总分']=Total
    names['考生编号'] = C_number
    names = names.sort_values(by='总分', ascending=False)#总分降序排序
    # names['序号'] = list(range(1, len(names['总分']) + 1))#重置序号

    # 保存结果
    SavePath = nameListFile.replace('.xls', '_done.xls')
    names.to_excel(SavePath, sheet_name='Sheet1',index=False, header=True)
    driver.quit()


def RecogVCode(VcodeFilename):
    """ 读取图片 """
    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()

    
    global APP_ID, API_KEY, SECRET_KEY
    # 初始化AipFace对象
    aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    # 定义参数变量
    options = {
        'detect_direction': 'false',
        'language_type': 'ENG',
    }
    try:
        # 调用通用文字识别接口
        if isinstance(VcodeFilename,str):
            ctt=get_file_content(VcodeFilename)
        else:
            ctt=VcodeFilename
        result = aipOcr.basicGeneral(ctt, options)
        if result['words_result_num']!=1:
            # print(result)
            return False
        rlt = result['words_result'][0]['words']
        if len(rlt)!=4:
            # print(result)
            return False

    except Exception:
        return False
    return rlt
    
    
    
if __name__ == '__main__':
    main()